using System;
using Game.Scripts.Entity;
using UnityEngine;
using UnityEngine.InputSystem;
using Zenject;

namespace Game.Scripts.Service
{
    public class PlayerInputService : MonoBehaviour
    {
        private PlayerInputActions playerInputActions;
        private Vector2 moveDirection;
        private InputAction move;
        private InputAction primaryContact;
        private InputAction primaryPosition;
        private IkunBus _ikunBus;
        private Vector2 initialPos;
        private Vector2 currentPos => primaryPosition.ReadValue<Vector2>();
        [SerializeField] private float swipeResistance = 20;
        [HideInInspector] public bool ifListenInput;





        [Inject]
        public void Construct(IkunBus ikunBus)
        {
            _ikunBus = ikunBus;
        }

        private void Awake()
        {
            ifListenInput = true;
            playerInputActions = new PlayerInputActions();
            move = playerInputActions.Player.Move;
            primaryContact = playerInputActions.Player.PrimaryContact;
            primaryPosition = playerInputActions.Player.PrimaryPostion;
            move.Enable();
            primaryContact.Enable();
            primaryPosition.Enable();
            move.performed += Move;
            primaryContact.performed += _ =>
            {
                initialPos = currentPos;
            };
            primaryContact.canceled += _ => DetectSwipe();
        }

        private void Move(InputAction.CallbackContext context)
        {
            if (!ifListenInput)
            {
                return;
            }
            moveDirection = context.ReadValue<Vector2>();
            if (moveDirection == Vector2.left)
            {
                _ikunBus.SetIkunBusPosition(IkunBusOperation.MoveLeft);
            }
            else if (moveDirection == Vector2.right)
            {
                _ikunBus.SetIkunBusPosition(IkunBusOperation.MoveRight);
            }
        }


        private void DetectSwipe()
        {
            if (!ifListenInput)
            {
                return;
            }
            Vector2 delta = currentPos - initialPos;
            if (Mathf.Abs(delta.x) > swipeResistance)
            {
                moveDirection.x = Mathf.Clamp(delta.x, -1, 1);
            }
            if (moveDirection == Vector2.left)
            {
                _ikunBus.SetIkunBusPosition(IkunBusOperation.MoveLeft);
            }
            else if (moveDirection == Vector2.right)
            {
                _ikunBus.SetIkunBusPosition(IkunBusOperation.MoveRight);
            }
        }


        private void OnDisable()
        {
            move.Disable();
            primaryContact.Disable();
            primaryPosition.Disable();
        }
    }
}